import Vue from 'vue';
import axios from 'axios';
import { getUrlSearchParams } from '@/utils/utils';
import { message } from 'ant-design-vue';
import { omit } from 'lodash';
import { CommonStore } from '@/store';
import { transformResponseForBigInt } from '@/utils/index';
import { setRequestTask, removeRequestTask } from '@/utils/request-tasks';

const ERRORS = [
  { code: '0', msg: '请求服务无法连接' },
  { code: '400', msg: '请求参数错误或错误请求' },
  { code: '401', msg: '身份验证错误' },
  { code: '404', msg: '找不到请求的地址' },
  { code: '415', msg: '请求的格式不受请求页面的支持' },
  { code: '450', msg: '登录失效，即将跳转到登录页面!' },
  { code: '500', msg: '服务器后台错误' },
  { code: '502', msg: '服务器网关错误' },
  { code: '504', msg: '请求超时' },
];

const _axios = axios.create({
  timeout: 60 * 1000,
  transformResponse: [transformResponseForBigInt],
});

_axios.interceptors.request.use(
  (config:any) => {
    if (['arraybuffer', 'blob'].includes(config.responseType!)) {
      config.transformResponse = [];
    }

    /**
     * 请求访问遮罩，禁止多次操作
     * store.progressTimerListPush 超2毫秒推入队列
     * store.loadingIdListPush 正在加载队列
     */
    let loadingId = new Date().getTime();
    // 需要在pinia挂载后再实例化
    const store = CommonStore();
    store.loadingIdListPush(loadingId);
    config.headers.token = store.token;
    const { data = {} } = config;
    const newData = {
      ...omit(data, ['requestTaskName', 'timeout']),
    };
    config.data = newData;
    // 修改 超时时长
    config.timeout = data.timeout || config.timeout;

    const controller = new AbortController();
    config.signal = controller.signal;
    // 任务加入队列
    setRequestTask(data?.requestTaskName, controller);

    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  },
);

// Add a response interceptor
_axios.interceptors.response.use(
  (response) => {
    //清除正在加载队列
    // 需要在pinia挂载后再实例化
    const store = CommonStore();
    store.loadingIdListPop();
    // console.log('response->', response);

    // 任务从队列移除
    const { config: { data: requestData = '{}' } = {} } = response || {};
    const parseRequestData = JSON.parse(requestData);
    removeRequestTask(parseRequestData?.requestTaskName);

    if (response.status == 200) {
      // code 为 10000，为后台默认自定义错误code，如果自己功能中有自定义错误出现，需要自己在代码里做处理
      if (response.data?.code != null && response.data?.code != 0 && response.data?.code !== 10000) {
        message.error(response.data?.status || response.data?.msg);
      }
      return response.config.responseType == 'arraybuffer' ? response : response.data;
    }
    return response.data;
  },
  (error) => {
    // 需要在pinia挂载后再实例化
    const store = CommonStore();
    store.loadingIdListPop();
    console.log('error->', error);
    console.log('error.response->', error.response);
    //清除正在加载队列列
    if (error.response) {
      // 任务从队列移除
      const { config: { data: requestData = '{}' } = {} } = error.response;
      const parseRequestData = JSON.parse(requestData);
      removeRequestTask(parseRequestData?.requestTaskName);

      // 请求已发出，但服务器响应的状态码不在 2xx 范围内
      let data = error.response.data;
      let status = error.response.status;
      if (status == '401' || status == 450) {
        setTimeout(function () {
          window.parent ? window.parent.location.replace('/') : window.location.replace('/');
        }, 1500);
      }
      //let  headers=error.response.headers;
      // 商品目录导入文件校验
      if (data.code == 'Dreg.PARAMS.ERROR') {
        message.error(data.message);
      } else {
        let Alert = ERRORS.find((item) => item.code == status);
        if (Alert != null) {
          message.error(Alert.msg);
        } else {
          message.error(status + ':' + data);
        }
      }
    } else {
      if (error?.message !== 'canceled') {
        message.error(ERRORS[0].msg);
      }
    }
    return Promise.reject(error?.response?.data || error);
  },
);

export default _axios;
